package com.novax.ex.activity.provider.controller;

import com.novax.ex.activity.infrastructure.entity.RankApply;
import com.novax.ex.activity.infrastructure.entity.RankConfig;
import com.novax.ex.activity.open.api.RankApplyApi;
import com.novax.ex.activity.provider.service.RankApplyService;
import com.novax.ex.activity.provider.service.RankConfigService;
import com.novax.ex.common.constant.InternationalCode;
import com.novax.ex.common.results.ReturnResult;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import java.util.Objects;

/**
 * @Description: 交易赛报名
 * @Author: ChenXi
 * @Date: 2023/11/27 14:24
 **/
@RestController
public class RankApplyController extends BaseActivityController implements RankApplyApi {

    @Resource
    private RankApplyService rankApplyService;
    @Resource
    private RankConfigService rankConfigService;

    @Override
    public ReturnResult<?> apply(String language, Long userId, Long rankId) {
        RankConfig openRankConfig = rankConfigService.findOpen();
        if(Objects.isNull(openRankConfig) || !openRankConfig.getId().equals(rankId)){
            // 只能报名开启中的活动
            return ReturnResult.fail(getInternational(language, InternationalCode.OPERATION_ERROR));
        }
        RankApply rankApply = new RankApply();
        rankApply.setUserId(userId);
        rankApply.setRankId(rankId);
        boolean flag;
        try {
            flag = rankApplyService.addSelective(rankApply);
        } catch (DuplicateKeyException e) {
            // 重复了则代表已经报过名了
            return ReturnResult.fail(getInternational(language, InternationalCode.RESUBMIT));
        }
        return flag ? ReturnResult.success(getInternational(language, InternationalCode.OPERATION_SUCCESS))
            : ReturnResult.fail(getInternational(language, InternationalCode.OPERATION_ERROR));

    }

    @Override
    public ReturnResult<Boolean> queryApply(Long userId, Long rankId) {
        return ReturnResult.success(Objects.nonNull(rankApplyService.queryApply(userId, rankId)));
    }

}
